package com.sqpoll.android.poll;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.sqpoll.android.R;
import com.sqpoll.android.util.AndroidUtil;
import com.sqpoll.android.widget.ExpandableHeightListView;

/**
 * The activity for creating new poll.
 * 
 * @author Younggue Bae
 */
public class PollCreateActivity extends SherlockFragmentActivity {

	public static final String TAG = "PollCreateActivity";
	
	private static final String TEMP_PHOTO_FILE = "temp.jpg";
	private static final int REQ_CODE_QUESTION_PICK_IMAGE = 100;
	private static final int REQ_CODE_QUESTION_TAKE_PHOTO = 200;
	private static final int REQ_CODE_ANSWER_PICK_IMAGE = 300;
	private static final int REQ_CODE_ANSWER_TAKE_PHOTO = 400;

	private Spinner mSpinnerQuestionType;
	private ArrayAdapter<CharSequence> mAdapterQuestionType;
	
	private ExpandableHeightListView mListViewAnswerChoice;
	private AnswerChoiceListAdapter mAdapterAnswerChoice;
	private ImageView mQuestionImage;
	private TableRow mQuestionMediaArea;
	private Button mButtonAddAnswerChoice;
	private Button mButtonSave;
	private Button mButtonNext;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_poll_create);

		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);

		mSpinnerQuestionType = (Spinner) findViewById(R.id.spinner_question_type);
		mAdapterQuestionType = ArrayAdapter.createFromResource(this, R.array.array_question_type,
				android.R.layout.simple_spinner_item);
		mAdapterQuestionType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinnerQuestionType.setAdapter(mAdapterQuestionType);
		mSpinnerQuestionType.setOnItemSelectedListener(mQuestionTyepSpinnerSelectedListener);
		

		// list type answer choice
		mListViewAnswerChoice = (ExpandableHeightListView) findViewById(R.id.list_view_answer_choice);
		mListViewAnswerChoice.setExpanded(true, false);

		mListViewAnswerChoice.setItemsCanFocus(true);
		mAdapterAnswerChoice = new AnswerChoiceListAdapter(Poll.MULTIPLE_CHOICE_TYPE);
		mListViewAnswerChoice.setAdapter(mAdapterAnswerChoice);

		mQuestionImage = (ImageView) findViewById(R.id.image_question);
		mButtonAddAnswerChoice = (Button) findViewById(R.id.button_add_answer_choice);
		mButtonAddAnswerChoice.setOnClickListener(mAddAnswerChoiceButtonClickListener);

		mQuestionMediaArea = (TableRow) findViewById(R.id.question_media_area);

		ImageButton buttonAttachMedia = (ImageButton) findViewById(R.id.button_attach_media);
		buttonAttachMedia.setOnClickListener(mAttachQuestionMediaButtonClickListener);
		
		mButtonSave = (Button) findViewById(R.id.button_save);
		mButtonSave.setOnClickListener(mSavePollButtonClickListener);
		mButtonNext = (Button) findViewById(R.id.button_next);
		mButtonNext.setOnClickListener(mNextButtonClickListener);
	}
	
	OnItemSelectedListener mQuestionTyepSpinnerSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			if (mAdapterQuestionType.getItem(position) ==  getString(R.string.question_type_rating)) {
				mAdapterAnswerChoice.setType(Poll.RATINGBAR_TYPE);
				
				mAdapterAnswerChoice.removeAll();
				AnswerChoice listItem = new AnswerChoice();
				mAdapterAnswerChoice.addItem(listItem);
				mAdapterAnswerChoice.notifyDataSetChanged();
				mButtonAddAnswerChoice.setVisibility(View.INVISIBLE);
			}
			else if (mAdapterQuestionType.getItem(position) ==  getString(R.string.question_type_multiple_choice)) {
				if (mAdapterAnswerChoice.getType().equals(Poll.RATINGBAR_TYPE)) {
					mAdapterAnswerChoice.setType(Poll.MULTIPLE_CHOICE_TYPE);
					
					mAdapterAnswerChoice.removeAll();
					for (int seq = 1; seq < 3; seq++) {
						AnswerChoice listItem = new AnswerChoice();
						mAdapterAnswerChoice.addItem(listItem);
					}	
					mAdapterAnswerChoice.notifyDataSetChanged();
					mButtonAddAnswerChoice.setVisibility(View.VISIBLE);
				}
			}
			else if (mAdapterQuestionType.getItem(position) ==  getString(R.string.question_type_single_choice)) {
				if (mAdapterAnswerChoice.getType().equals(Poll.RATINGBAR_TYPE)) {
					mAdapterAnswerChoice.setType(Poll.SINGLE_CHOICE_TYPE);
					
					mAdapterAnswerChoice.removeAll();
					for (int seq = 1; seq < 3; seq++) {
						AnswerChoice listItem = new AnswerChoice();
						mAdapterAnswerChoice.addItem(listItem);
					}	
					mAdapterAnswerChoice.notifyDataSetChanged();
					mButtonAddAnswerChoice.setVisibility(View.VISIBLE);
				}
			}
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
	};

	OnClickListener mAddAnswerChoiceButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			AnswerChoice listItem = new AnswerChoice();
			mAdapterAnswerChoice.addItem(listItem);
			mAdapterAnswerChoice.notifyDataSetChanged();
		}
	};

	OnClickListener mAttachQuestionMediaButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d(TAG, "Click: Attach media button at question");
	
			AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
			builder.setTitle(R.string.dialog_title_attach_media).setItems(R.array.array_attach_media,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (which == 0) {
								showPhotoGallery(REQ_CODE_QUESTION_PICK_IMAGE);
							}
							else if (which == 1) {
								takePhoto(REQ_CODE_QUESTION_TAKE_PHOTO);
							}
							
						}
					});
			builder.create().show();
		}
	};
	
	OnClickListener mSavePollButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
		}
	};
	
	OnClickListener mNextButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(getBaseContext(), PollTargetActivity.class);
			startActivity(intent);
		}
	};

	/**
	 * Resizes the image proportionately so it fits the entire space.
	 */
	@SuppressWarnings("deprecation")
	private void setImageBitmap(Drawable d, ImageView imageView) {
		float width = getWindowManager().getDefaultDisplay().getWidth();

		BitmapDrawable drawable = (BitmapDrawable) d;
		Bitmap bitmap = drawable.getBitmap();

		float i = ((float) width) / ((float) bitmap.getWidth());
		float imageHeight = i * (bitmap.getHeight());
		TableRow.LayoutParams params = (TableRow.LayoutParams) imageView.getLayoutParams();
		params.height = (int) imageHeight;
		params.width = (int) width;
		imageView.setLayoutParams(params);
		imageView.setImageDrawable(d);
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_poll_create, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		
		/*	
		case R.id.menu_save:
			Toast.makeText(getBaseContext(), "Selected: Save poll", Toast.LENGTH_SHORT).show();
			break;
		*/
		}

		return true;
	}

	/**
	 * Adapter for answer choice list.
	 *
	 */
	public class AnswerChoiceListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private String mType;
		private ArrayList<AnswerChoice> mItems = new ArrayList<AnswerChoice>();

		public AnswerChoiceListAdapter(String type) {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mType = type;
			for (int seq = 1; seq < 3; seq++) {
				AnswerChoice listItem = new AnswerChoice();
				listItem.setSequence(seq);
				mItems.add(listItem);
			}
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mItems.size();
		}

		@Override
		public Object getItem(int position) {
			return mItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		public void setType(String type) {
			this.mType = type;
		}
		
		public String getType() {
			return this.mType;
		}
		
		public void addItem(AnswerChoice listItem) {
			int seq = getCount() + 1;

			if (seq > 20) {
				return;
			}
			listItem.setSequence(getCount() + 1);

			mItems.add(listItem);
		}

		public void removeItem(int position) {
			mItems.remove(position);
		}
		
		public void removeAll() {
			mItems.clear();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.list_item_answer_choice_create, null);
				
				holder.mLayoutAnswerChoiceText = (LinearLayout) convertView.findViewById(R.id.layout_answer_choice_text);
				holder.mLayoutAnswerChoiceRatingBar = (LinearLayout) convertView.findViewById(R.id.layout_answer_choice_ratingbar);
				
				holder.mSequence = (TextView) convertView.findViewById(R.id.sequence);
				
				holder.mAnswerChoiceName = (EditText) convertView.findViewById(R.id.answer_choice_name);
				holder.mAnswerChoiceRatingBar = (RatingBar) convertView.findViewById(R.id.answer_choice_ratingbar);
				
				holder.mButtonAttachMedia = (ImageButton) convertView.findViewById(R.id.button_attach_media);
				holder.mLayoutAnswerChoiceMedia = (LinearLayout) convertView.findViewById(R.id.layout_answer_choice_media);
				holder.mAnswerChoiceImage = (ImageView) convertView.findViewById(R.id.image_answer_choice);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			AnswerChoice listItem = mItems.get(position);
			int seq = listItem.getSequence();
			String strSeq = "";
			if (seq < 10) {
				strSeq = "" + seq + "  ";
			} else {
				strSeq = "" + seq + "";
			}

			holder.mSequence.setText(strSeq);
			holder.mAnswerChoiceName.setId(position);
			holder.mButtonAttachMedia.setId(position);
			
			if (mType.equals(Poll.MULTIPLE_CHOICE_TYPE) || mType.equals(Poll.SINGLE_CHOICE_TYPE)) {
				holder.mLayoutAnswerChoiceText.setVisibility(View.VISIBLE);
				holder.mLayoutAnswerChoiceRatingBar.setVisibility(View.INVISIBLE);
				
				ViewGroup.LayoutParams params = holder.mLayoutAnswerChoiceRatingBar.getLayoutParams();
				params.height = 0;
			}
			else if (mType.equals(Poll.RATINGBAR_TYPE)) {
				holder.mLayoutAnswerChoiceText.setVisibility(View.INVISIBLE);
				holder.mLayoutAnswerChoiceRatingBar.setVisibility(View.VISIBLE);
				
				ViewGroup.LayoutParams params = holder.mLayoutAnswerChoiceRatingBar.getLayoutParams();
				//params.height = holder.mAnswerChoiceName.getMeasuredHeight() + 150;
				float ratingbarHeight = AndroidUtil.convertDpToPixel(50, convertView.getContext());
				params.height = (int) ratingbarHeight;
			}

			Drawable image = listItem.getImage();
			if (image != null) {
				holder.mLayoutAnswerChoiceMedia.setVisibility(View.VISIBLE);
				setAnswerChoiceImageBitmap(image, holder.mAnswerChoiceImage);
			} else {
				holder.mLayoutAnswerChoiceMedia.setVisibility(View.INVISIBLE);
				LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.mAnswerChoiceImage.getLayoutParams();
				params.height = 0;
				holder.mAnswerChoiceImage.setLayoutParams(params);
				holder.mAnswerChoiceImage.setImageDrawable(null);
			}

			// we need to update adapter once we finish with editing
			holder.mAnswerChoiceName.setOnFocusChangeListener(new OnFocusChangeListener() {
				public void onFocusChange(View v, boolean hasFocus) {
					if (!hasFocus) {
						final int position = v.getId();
						final EditText name = (EditText) v;
						Log.d(TAG, "EditText at position = " + position);
						
						if (mItems.size() > position) {
							AnswerChoice listItem = mItems.get(position);
							listItem.setName(name.getText().toString());
						}
					}
				}
			});

			holder.mButtonAttachMedia.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int position = v.getId();
					Log.d(TAG, "Click: Attach media button at position = " + position);
					getIntent().putExtra("position", position);

					AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
					builder.setTitle(R.string.dialog_title_attach_media).setItems(R.array.array_attach_media,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									if (which == 0) {
										showPhotoGallery(REQ_CODE_ANSWER_PICK_IMAGE);
									}
									else if (which == 1) {
										takePhoto(REQ_CODE_ANSWER_TAKE_PHOTO);
									}
									
								}
							});
					builder.create().show();
				}
			});

			return convertView;
		}
		
		/**
		 * Resizes the image proportionately so it fits the entire space.
		 */
		@SuppressWarnings("deprecation")
		private void setAnswerChoiceImageBitmap(Drawable d, ImageView imageView) {
			float width = getWindowManager().getDefaultDisplay().getWidth();

			BitmapDrawable drawable = (BitmapDrawable) d;
			Bitmap bitmap = drawable.getBitmap();

			float i = ((float) width) / ((float) bitmap.getWidth());
			float imageHeight = i * (bitmap.getHeight());
			LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageView.getLayoutParams();
			params.height = (int) imageHeight;
			params.width = (int) width;
			imageView.setLayoutParams(params);
			imageView.setImageDrawable(d);
		}
	}
	
	/**
	 * View holder for a list item.
	 *
	 */
	class ViewHolder {

		LinearLayout mLayoutAnswerChoiceText;
		LinearLayout mLayoutAnswerChoiceRatingBar;
		TextView mSequence;
		EditText mAnswerChoiceName;
		RatingBar mAnswerChoiceRatingBar;
		ImageButton mButtonAttachMedia;
		ImageView mAnswerChoiceImage;
		LinearLayout mLayoutAnswerChoiceMedia;
	}
	
	private void showPhotoGallery(int requestCode) {
		String action = Intent.ACTION_GET_CONTENT;
		Uri uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		Intent intent = new Intent(action, uri);
		
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		
		startActivityForResult(intent, requestCode);
	}
	
	private void takePhoto(int requestCode) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		startActivityForResult(intent, requestCode);
	}
	
	/**
	 * Returns the route of temporary file.
	 */
	private Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}

	/**
	 * Returns the route of file in SDCARD.
	 */
	private File getTempFile() {
		if (isSdcardMounted()) {
			File f = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE);
			try {
				f.createNewFile();
			} catch (IOException e) {
			}
			return f;
		} else
			return null;
	}
	
	/**
	 * Checks if SDCARD is mounted or not.
	 * @return
	 */
	private boolean isSdcardMounted() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;

		return false;
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent imageData) {
		super.onActivityResult(requestCode, resultCode, imageData);
		
		switch (requestCode) {
		case REQ_CODE_QUESTION_PICK_IMAGE:
			if (resultCode == RESULT_OK) {
				if (imageData != null) {
					File filePath = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE);
					Log.d(TAG, "onActivityResult: path = " + filePath.getPath());

					mQuestionMediaArea.setVisibility(View.VISIBLE);
					// decoding from temp.jpg to bitmap
					Bitmap bitmap = BitmapFactory.decodeFile(filePath.getPath());
					Drawable drawable = new BitmapDrawable(getResources(), bitmap);
					setImageBitmap(drawable, mQuestionImage);	
				}
			}
			break;
		case REQ_CODE_QUESTION_TAKE_PHOTO:
			if (resultCode == RESULT_OK) {
				Bitmap bitmap = (Bitmap) imageData.getExtras().get("data");

				mQuestionMediaArea.setVisibility(View.VISIBLE);
				Drawable drawable = new BitmapDrawable(getResources(), bitmap);
				setImageBitmap(drawable, mQuestionImage);
			}
			break;
		case REQ_CODE_ANSWER_PICK_IMAGE:
			if (resultCode == RESULT_OK) {
				if (imageData != null) {
					int position = getIntent().getExtras().getInt("position");
					Log.d(TAG, "onActivityResult: position = " + position);
					
					File filePath = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE);
					Log.d(TAG, "onActivityResult: path = " + filePath.getPath());

					// decoding from temp.jpg to bitmap
					Bitmap bitmap = BitmapFactory.decodeFile(filePath.getPath());
					
					AnswerChoice listItem = (AnswerChoice) mAdapterAnswerChoice.getItem(position);
					Drawable drawable = new BitmapDrawable(getResources(), bitmap);
					listItem.setImage(drawable);

					mAdapterAnswerChoice.notifyDataSetChanged();
				}
			}
			break;
		case REQ_CODE_ANSWER_TAKE_PHOTO:
			if (resultCode == RESULT_OK) {
				int position = getIntent().getExtras().getInt("position");
				Log.d(TAG, "onActivityResult: position = " + position);
				
				Bitmap bitmap = (Bitmap) imageData.getExtras().get("data");

				AnswerChoice listItem = (AnswerChoice) mAdapterAnswerChoice.getItem(position);
				Drawable image = new BitmapDrawable(getResources(), bitmap);
				listItem.setImage(image);

				mAdapterAnswerChoice.notifyDataSetChanged();
			}
			break;
		}
	}


}